package com.cloudlead.common.lang.persistence;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Will on 2015/12/10.
 */
public class OnlineUser {
    private final static OnlineUser onlineUser =new OnlineUser();
    private Date lastTime = new Date();
    private List<Map> list = new ArrayList<Map>();
    public static OnlineUser getInstance(){return onlineUser;}
    private  final static Long refreshTime = 3600000l;
    private  final static Long expireTime = 3600000l;
    public List<Map> getList() {
        return list;
    }
    public  static String updateTime(String userName){
        try{
            List<Map> list1 = OnlineUser.getInstance().getList();
            Date date = new Date();
            SimpleDateFormat myFmt=new SimpleDateFormat("yy/MM/dd HH:mm:ss");
            if(OnlineUser.getInstance().TimeCalc(date)>=refreshTime){
                if(!list1.isEmpty()){
                    for(int i=0;i<list1.size();i++){
                        try {
                            if(date.getTime()-myFmt.parse(list1.get(i).get("onlineTime").toString()).getTime()>=expireTime){
                                list1.remove(i);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    OnlineUser.getInstance().lastTime = date;
                }
            }
            Map map = new HashMap<>();
            map.put("userName",userName);
            for(Map temp : list1){
                Boolean b = temp.containsValue(userName);
                if(b){
                    temp.replace("onlineTime",myFmt.format(date));
                    return null;
                }
            }
            map.put("onlineTime",myFmt.format(date));
            list1.add(map);
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    private Long TimeCalc(Date date){
        return date.getTime() - OnlineUser.getInstance().lastTime.getTime();
    }
}
